'use strict';

const Service = require('egg').Service;
const jwt = require('jsonwebtoken');
const _priKey = `-----BEGIN RSA PRIVATE KEY-----
                MIICWwIBAAKBgQDGNrzOW3wuyy88mWM5C5pWXhP5IukJUu3j7cUnYHGsCQeuH2Dj
                YXnub583DWeaUN1hpNPHvAXfXj8Zl8/E/VZv3NLyejs4o6g1wCP1msTRKubJwznX
                Lza6tnwAo6/IjpnR5/ngOSdsPtz8QYcpC9VF4MZA35uaZLBqUwzBkI3gSwIDAQAB
                AoGAWL2W6BhjT5veCRZvKtH8BiDWdlrf1DHRmZMRCmEOY0QjsRwRR5uTeGF2+bHB
                qX/8rUObITgXtPo/69hgx8PYFzEEuUh/5Z/9Lk8Ky2X6OgnxWjHX4qzRudYeFu0i
                c/JF4Mh/oSkAS/u1rNxQEpj6lKo5Q7gNBZK9jJRC9aHc6AkCQQDpZqVw5e119+D7
                N/XefUopCsqwWwz5Llj5tiQdOZrXwgOmlGltbn8DFhTbJVJSn2fc8zL9ymXKcCyF
                JkA1LEkHAkEA2WfmoRgYcZIoUnmprs+wgHkY7tFiPyNcyqwmA46pAm3bjI79QEsC
                Znipc9zllyWAlKjwbrgoyEG7CSfmaU9xnQJAd9b+h3Nnc7TszdCz66NFGsGxxM9b
                X+5OPRkqfd8ABFxX54Y4g7nCeWEzIDqPhGDYwXgV7H2pukHSeiNjwGmWrQJAJb9f
                kOrxG48IB0Huj1aqS7Q6+wRJ7bKDIwF+3DFB8RUIAMC3AhnEAezDZ0Wca4DscWNf
                06mQEy0uf2l5HSHZFQJAYaTZwR4vhv4YxlE8dy7fhEijzlWIkBn4BdP+8rZiEf9c
                zMbeB5BGGPcseGt08EqK1wYPjh5N3nEUumS/KkFAfQ==
                -----END RSA PRIVATE KEY-----`;

class loginService extends Service {

	//登陆
	async login(param) {
		const {
			app,
			ctx
		} = this;
		const result = {};
		// 验证账号密码
		let isLogin = await app.mysql.query(`SELECT * from login_user where login_name='${param.user}' and password='${param.password}'`);
		console.log("----------------isLogin------------------")
		console.log(isLogin)
		console.log("----------------isLogin------------------")

		if (!isLogin[0]) {
			return await ctx.helper.basicode(0, { token: null });
		}
		// 判断权限
		let token = jwt.sign({
			data: {
				user: param.user,
				password: param.password,
				isLogin: true
			}
		}, _priKey, { expiresIn: '1h' });
		console.log("----------------token------------------")
		console.log(token)
		console.log("----------------token------------------")
		result.token = token;
		return await ctx.helper.basicode(0, result);
	};

	//	token验证
	async tokenCheck(params) {
		const {
			ctx
		} = this;
		try {
			let result = true;
			// token验证
			console.log("----------------decoded------------------")
			console.log(params)
			console.log("----------------decoded------------------")
			
			return await ctx.helper.basicode(0, params);
		} catch (e) {
			console.log("*****    loginService--tokenCheck-error:", e);
			return await ctx.helper.basicode(0, false);
		}
	};
}

module.exports = loginService;
